package com.example.demo.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public Set<String> keys(String keys){
        try {
            return redisTemplate.keys(keys);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取普通缓存
     * @param key 键
     * @return 值
     */
    public Object get(String key){
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 存入普通缓存
     * @param key
     * @param value
     * @return 返回结果 成功 true  失败 false
     */
    public boolean set(String key ,Object value){
        try{
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 存入数据且设置有效时常
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean setT(String key, Object value ,Long time){
        try {
            redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置有效时常
     * @param key
     * @param value
     * @return
     */
    public boolean expire(String key ,Long value){
        try {
            redisTemplate.expire(key, value , TimeUnit.SECONDS);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    public Long getExpireByKey(String key){
        try{
            return redisTemplate.getExpire(key,TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 存放缓存，存在返回结果，不存在放入
     * @param key
     * @param value
     * @return
     */
    public boolean setnx(String key, Object value){
        try {
            redisTemplate.opsForValue().setIfAbsent(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public boolean hashKey(String key ){
        try {
            return redisTemplate.hasKey(key);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


}
